package com.zj.leetcode.medium.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: algorithm
 * @description: 二叉树展开为链表
 * 114 flatten-binary-tree-to-linked-list
 * @author: Zhang Bo
 * @create: 2022-01-14 17:05
 **/
public class FlattenBinaryTreeToLinkedList {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1, new TreeNode(2, new TreeNode(3), new TreeNode(4)), new TreeNode(5, null, new TreeNode(6)));
        Solution solution = new FlattenBinaryTreeToLinkedList().new Solution();
        solution.flatten(root);


    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        List<Integer> list = new ArrayList<>();

        public void flatten(TreeNode root) {

            this.dfs(root);
            for (int i = 0; i < list.size(); i++) {
                TreeNode temp = new TreeNode(list.get(i));
                root.left = null;
                root.right = temp;
                root = root.right;
            }

            System.out.println(root);
        }

        public void dfs(TreeNode node) {
            if (node != null) {
                list.add(node.val);
                if (node.left != null) {
                    this.dfs(node.left);
                }
                if (node.right != null) {
                    this.dfs(node.right);
                }
            }

        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
